package Test_Transaction;

import util.jdbc_utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//使用jdbc 操作事务
public class Test_01 {
    //执行成功
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;

        String sql = "update `account` set money =money+500.00 where name ='A';";
        String sql2 = "update  `account` set money=money-500.00 where name ='B';";

        try {
            connection = jdbc_utils.get_connection();
            //关闭事务的自动提交，自动会开启事务 不需要：（start transaction）
            connection.setAutoCommit(false);
            statement = connection.prepareStatement(sql);
            statement.executeUpdate();

            statement= connection.prepareStatement(sql2);
            statement.executeUpdate();

            //业务完毕，提交事务
            connection.commit();
            System.out.println("成功！");

        } catch (SQLException throwables) {
            //发生错误，程序根本没走这里，直接在上方就报错
            throwables.printStackTrace();
            try {
                //不成功，回滚
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } finally {
            try {
                jdbc_utils.release(connection, statement, null);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }



    }
}
